<template>
  <div class="system-config-container">
    <div class="page-header">
      <h2>系统配置管理</h2>
      <p>管理系统的各项配置参数</p>
    </div>

    <!-- 配置分组标签页 -->
    <el-tabs v-model="activeGroup" @tab-click="handleGroupChange" @tab-change="handleTabChange">
      <el-tab-pane label="邮箱配置" name="EMAIL">
        <div class="config-section">
          <div class="section-header">
            <h3>邮箱功能配置</h3>
            <p>配置邮箱注册和登录功能</p>
          </div>
          
          <el-form :model="emailConfig" label-width="150px" class="config-form">
            <el-form-item label="邮箱功能">
              <el-switch
                v-model="emailConfig.enabled"
                @change="updateConfig('email.enabled', emailConfig.enabled)"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="config-desc">启用后可使用邮箱相关功能</div>
            </el-form-item>
            
            <el-form-item label="邮箱注册">
              <el-switch
                v-model="emailConfig.registerEnabled"
                @change="updateConfig('email.register.enabled', emailConfig.registerEnabled)"
                :disabled="!emailConfig.enabled"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="config-desc">允许用户通过邮箱验证码注册</div>
            </el-form-item>
            
            <el-form-item label="邮箱登录">
              <el-switch
                v-model="emailConfig.loginEnabled"
                @change="updateConfig('email.login.enabled', emailConfig.loginEnabled)"
                :disabled="!emailConfig.enabled"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="config-desc">允许用户通过邮箱验证码登录</div>
            </el-form-item>
            
            <el-form-item label="验证码过期时间">
              <el-input-number
                v-model="emailConfig.codeExpire"
                @change="updateConfig('email.code.expire', emailConfig.codeExpire)"
                :min="60"
                :max="3600"
                :step="60"
                controls-position="right"
                style="width: 200px"
              />
              <span style="margin-left: 10px">秒</span>
              <div class="config-desc">邮箱验证码的有效期（60-3600秒）</div>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 手机号功能配置 -->
      <el-tab-pane label="手机号配置" name="PHONE">
        <div class="config-section">
          <div class="section-header">
            <h3>手机号功能配置</h3>
            <p>配置手机号注册、登录等功能参数</p>
          </div>

          <el-form :model="phoneConfig" label-width="150px" class="config-form">
            <el-form-item label="手机号功能">
              <el-switch
                v-model="phoneConfig.enabled"
                @change="updateConfig('phone.enabled', phoneConfig.enabled)"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="config-desc">启用后可使用手机号相关功能</div>
            </el-form-item>

            <el-form-item label="手机号注册">
              <el-switch
                v-model="phoneConfig.registerEnabled"
                @change="updateConfig('phone.register.enabled', phoneConfig.registerEnabled)"
                :disabled="!phoneConfig.enabled"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="config-desc">允许用户通过手机号验证码注册</div>
            </el-form-item>

            <el-form-item label="手机号登录">
              <el-switch
                v-model="phoneConfig.loginEnabled"
                @change="updateConfig('phone.login.enabled', phoneConfig.loginEnabled)"
                :disabled="!phoneConfig.enabled"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="config-desc">允许用户通过手机号验证码登录</div>
            </el-form-item>

            <el-form-item label="验证码过期时间">
              <el-input-number
                v-model="phoneConfig.codeExpire"
                @change="updateConfig('phone.code.expire', phoneConfig.codeExpire)"
                :min="60"
                :max="3600"
                :step="60"
                controls-position="right"
                style="width: 200px"
              />
              <span style="margin-left: 10px">秒</span>
              <div class="config-desc">短信验证码的有效期（60-3600秒）</div>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <el-tab-pane label="验证码配置" name="CAPTCHA">
        <div class="config-section">
          <div class="section-header">
            <h3>验证码功能配置</h3>
            <p>配置登录和注册时的验证码功能</p>
          </div>

          <el-card class="config-card">
            <template #header>
              <div class="card-header">
                <span>验证码功能开关</span>
              </div>
            </template>

            <div class="config-item">
              <div class="config-label">
                <span>启用验证码功能</span>
                <el-tooltip content="是否启用系统验证码功能" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-switch
                v-model="captchaConfig.enabled"
                @change="updateConfig('captcha.enabled', captchaConfig.enabled)"
              />
            </div>

            <div class="config-item" v-if="captchaConfig.enabled">
              <div class="config-label">
                <span>登录验证码</span>
                <el-tooltip content="账号密码登录时是否需要验证码" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-switch
                v-model="captchaConfig.loginEnabled"
                @change="updateConfig('captcha.login.enabled', captchaConfig.loginEnabled)"
              />
            </div>

            <div class="config-item" v-if="captchaConfig.enabled">
              <div class="config-label">
                <span>注册验证码</span>
                <el-tooltip content="用户注册时是否需要验证码" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-switch
                v-model="captchaConfig.registerEnabled"
                @change="updateConfig('captcha.register.enabled', captchaConfig.registerEnabled)"
              />
            </div>
          </el-card>

          <el-card class="config-card" v-if="captchaConfig.enabled">
            <template #header>
              <div class="card-header">
                <span>验证码类型配置</span>
              </div>
            </template>

            <div class="config-item">
              <div class="config-label">
                <span>验证码类型</span>
                <el-tooltip content="选择验证码的类型" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-select
                v-model="captchaConfig.type"
                @change="updateConfig('captcha.type', captchaConfig.type)"
                style="width: 200px"
              >
                <el-option label="图片验证码" value="image" />
                <el-option label="数学运算验证码" value="math" />
                <el-option label="滑块验证码" value="slider" />
              </el-select>
            </div>

            <div class="config-item">
              <div class="config-label">
                <span>验证码过期时间</span>
                <el-tooltip content="验证码的有效期（秒）" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-input-number
                v-model="captchaConfig.expire"
                @change="updateConfig('captcha.expire', captchaConfig.expire)"
                :min="60"
                :max="3600"
                :step="30"
                style="width: 200px"
              />
              <span class="unit">秒</span>
            </div>
          </el-card>

          <el-card class="config-card" v-if="captchaConfig.enabled && (captchaConfig.type === 'image' || captchaConfig.type === 'math')">
            <template #header>
              <div class="card-header">
                <span>图片验证码配置</span>
              </div>
            </template>

            <div class="config-item">
              <div class="config-label">
                <span>验证码长度</span>
                <el-tooltip content="图片验证码的字符长度" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-input-number
                v-model="captchaConfig.length"
                @change="updateConfig('captcha.length', captchaConfig.length)"
                :min="3"
                :max="8"
                style="width: 200px"
              />
              <span class="unit">位</span>
            </div>

            <div class="config-item">
              <div class="config-label">
                <span>验证码宽度</span>
                <el-tooltip content="验证码图片的宽度（像素）" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-input-number
                v-model="captchaConfig.width"
                @change="updateConfig('captcha.width', captchaConfig.width)"
                :min="80"
                :max="200"
                :step="10"
                style="width: 200px"
              />
              <span class="unit">px</span>
            </div>

            <div class="config-item">
              <div class="config-label">
                <span>验证码高度</span>
                <el-tooltip content="验证码图片的高度（像素）" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-input-number
                v-model="captchaConfig.height"
                @change="updateConfig('captcha.height', captchaConfig.height)"
                :min="30"
                :max="80"
                :step="5"
                style="width: 200px"
              />
              <span class="unit">px</span>
            </div>

            <div class="config-item">
              <div class="config-label">
                <span>启用干扰线</span>
                <el-tooltip content="是否在验证码图片中添加干扰线" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-switch
                v-model="captchaConfig.noiseEnabled"
                @change="updateConfig('captcha.noise.enabled', captchaConfig.noiseEnabled)"
              />
            </div>

            <div class="config-item">
              <div class="config-label">
                <span>大小写敏感</span>
                <el-tooltip content="验证码是否区分大小写" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <el-switch
                v-model="captchaConfig.caseSensitive"
                @change="updateConfig('captcha.case.sensitive', captchaConfig.caseSensitive)"
              />
            </div>
          </el-card>

          <!-- 验证码预览 -->
          <el-card class="config-card" v-if="captchaConfig.enabled">
            <template #header>
              <div class="card-header">
                <span>验证码预览</span>
              </div>
            </template>

            <div class="captcha-preview">
              <CaptchaComponent
                :type="captchaConfig.type"
                :required="true"
                @verify-success="handlePreviewSuccess"
                @verify-failed="handlePreviewFailed"
              />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="系统配置" name="SYSTEM">
        <div class="config-section">
          <div class="section-header">
            <h3>系统基础配置</h3>
            <p>系统运行的基础参数配置</p>
          </div>

          <el-alert
            title="功能开发中"
            type="info"
            description="系统基础配置功能正在开发中，敬请期待..."
            show-icon
            :closable="false"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 配置状态显示 -->
    <div class="config-status" v-if="activeGroup === 'EMAIL'">
      <el-card>
        <template #header>
          <span>当前邮箱功能状态</span>
        </template>
        <div class="status-grid">
          <div class="status-item">
            <el-tag :type="emailConfig.enabled ? 'success' : 'danger'">
              邮箱功能：{{ emailConfig.enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </div>
          <div class="status-item">
            <el-tag :type="emailConfig.registerEnabled && emailConfig.enabled ? 'success' : 'info'">
              邮箱注册：{{ emailConfig.registerEnabled && emailConfig.enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </div>
          <div class="status-item">
            <el-tag :type="emailConfig.loginEnabled && emailConfig.enabled ? 'success' : 'info'">
              邮箱登录：{{ emailConfig.loginEnabled && emailConfig.enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </div>
          <div class="status-item">
            <el-tag type="info">
              验证码过期：{{ emailConfig.codeExpire }}秒
            </el-tag>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 手机号配置状态显示 -->
    <div class="config-status" v-if="activeGroup === 'PHONE'">
      <el-card>
        <template #header>
          <span>当前手机号功能状态</span>
        </template>
        <div class="status-grid">
          <div class="status-item">
            <el-tag :type="phoneConfig.enabled ? 'success' : 'danger'">
              手机号功能：{{ phoneConfig.enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </div>
          <div class="status-item">
            <el-tag :type="phoneConfig.registerEnabled && phoneConfig.enabled ? 'success' : 'info'">
              手机号注册：{{ phoneConfig.registerEnabled && phoneConfig.enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </div>
          <div class="status-item">
            <el-tag :type="phoneConfig.loginEnabled && phoneConfig.enabled ? 'success' : 'info'">
              手机号登录：{{ phoneConfig.loginEnabled && phoneConfig.enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </div>
          <div class="status-item">
            <el-tag type="info">
              验证码过期：{{ phoneConfig.codeExpire }}秒
            </el-tag>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
import { getConfigsByGroup, batchUpdateConfigs } from '../../api/systemConfig'
import { getCaptchaConfigStatus } from '../../api/captcha'
import CaptchaComponent from '../../components/CaptchaComponent.vue'

// 从localStorage恢复上次选中的标签页，默认为EMAIL
const savedGroup = localStorage.getItem('systemConfigActiveGroup')
const activeGroup = ref(savedGroup && ['EMAIL', 'PHONE', 'CAPTCHA', 'SYSTEM'].includes(savedGroup) ? savedGroup : 'EMAIL')

// 邮箱配置
const emailConfig = reactive({
  enabled: false,
  registerEnabled: false,
  loginEnabled: false,
  codeExpire: 300
})

// 手机号配置
const phoneConfig = reactive({
  enabled: false,
  registerEnabled: false,
  loginEnabled: false,
  codeExpire: 300
})

// 验证码功能配置
const captchaConfig = reactive({
  enabled: true,
  loginEnabled: true,
  registerEnabled: false,
  type: 'image',
  expire: 300,
  length: 4,
  width: 120,
  height: 40,
  noiseEnabled: true,
  caseSensitive: false
})

// 加载邮箱配置数据
const loadEmailConfigs = async () => {
  try {
    console.log('开始加载邮箱配置...')
    const response = await getConfigsByGroup('EMAIL')
    const configs = response.data
    console.log('邮箱配置数据:', configs)

    // 解析配置数据
    configs.forEach(config => {
      switch (config.configKey) {
        case 'email.enabled':
          emailConfig.enabled = config.configValue === 'true'
          break
        case 'email.register.enabled':
          emailConfig.registerEnabled = config.configValue === 'true'
          break
        case 'email.login.enabled':
          emailConfig.loginEnabled = config.configValue === 'true'
          break
        case 'email.code.expire':
          emailConfig.codeExpire = parseInt(config.configValue) || 300
          break
      }
    })
    console.log('邮箱配置加载完成:', emailConfig)
  } catch (error) {
    console.error('加载邮箱配置失败:', error)
    ElMessage.error('加载邮箱配置失败')
  }
}

// 加载手机号配置数据
const loadPhoneConfigs = async () => {
  try {
    console.log('开始加载手机号配置...')
    const response = await getConfigsByGroup('PHONE')
    const configs = response.data
    console.log('手机号配置数据:', configs)

    // 解析配置数据
    configs.forEach(config => {
      switch (config.configKey) {
        case 'phone.enabled':
          phoneConfig.enabled = config.configValue === 'true'
          break
        case 'phone.register.enabled':
          phoneConfig.registerEnabled = config.configValue === 'true'
          break
        case 'phone.login.enabled':
          phoneConfig.loginEnabled = config.configValue === 'true'
          break
        case 'phone.code.expire':
          phoneConfig.codeExpire = parseInt(config.configValue) || 300
          break
      }
    })
    console.log('手机号配置加载完成:', phoneConfig)
  } catch (error) {
    console.error('加载手机号配置失败:', error)
    ElMessage.error('加载手机号配置失败')
  }
}

// 加载验证码配置数据
const loadCaptchaConfigs = async () => {
  try {
    console.log('开始加载验证码配置...')
    const response = await getConfigsByGroup('CAPTCHA')
    const configs = response.data
    console.log('验证码配置数据:', configs)

    // 解析配置数据
    configs.forEach(config => {
      switch (config.configKey) {
        case 'captcha.enabled':
          captchaConfig.enabled = config.configValue === 'true'
          break
        case 'captcha.login.enabled':
          captchaConfig.loginEnabled = config.configValue === 'true'
          break
        case 'captcha.register.enabled':
          captchaConfig.registerEnabled = config.configValue === 'true'
          break
        case 'captcha.type':
          captchaConfig.type = config.configValue || 'image'
          break
        case 'captcha.expire':
          captchaConfig.expire = parseInt(config.configValue) || 300
          break
        case 'captcha.length':
          captchaConfig.length = parseInt(config.configValue) || 4
          break
        case 'captcha.width':
          captchaConfig.width = parseInt(config.configValue) || 120
          break
        case 'captcha.height':
          captchaConfig.height = parseInt(config.configValue) || 40
          break
        case 'captcha.noise.enabled':
          captchaConfig.noiseEnabled = config.configValue === 'true'
          break
        case 'captcha.case.sensitive':
          captchaConfig.caseSensitive = config.configValue === 'true'
          break
      }
    })
    console.log('验证码配置加载完成:', captchaConfig)
  } catch (error) {
    console.error('加载验证码配置失败:', error)
    ElMessage.error('加载验证码配置失败')
  }
}

// 更新单个配置
const updateConfig = async (configKey, value) => {
  try {
    const configValue = typeof value === 'boolean' ? value.toString() : value.toString()

    await batchUpdateConfigs({
      [configKey]: configValue
    })

    ElMessage.success('配置更新成功')

    // 配置更新成功后，延迟一下重新加载配置以确保数据同步
    setTimeout(() => {
      if (activeGroup.value === 'EMAIL') {
        loadEmailConfigs()
      } else if (activeGroup.value === 'PHONE') {
        loadPhoneConfigs()
      } else if (activeGroup.value === 'CAPTCHA') {
        loadCaptchaConfigs()
      }
    }, 500)

  } catch (error) {
    console.error('更新配置失败:', error)
    ElMessage.error('更新配置失败')
    // 重新加载配置以恢复状态
    if (activeGroup.value === 'EMAIL') {
      await loadEmailConfigs()
    } else if (activeGroup.value === 'PHONE') {
      await loadPhoneConfigs()
    } else if (activeGroup.value === 'CAPTCHA') {
      await loadCaptchaConfigs()
    }
  }
}

// 切换分组
const handleGroupChange = (tab) => {
  // 保存当前选中的标签页到localStorage
  localStorage.setItem('systemConfigActiveGroup', tab.name)

  if (tab.name === 'EMAIL') {
    loadEmailConfigs()
  } else if (tab.name === 'PHONE') {
    loadPhoneConfigs()
  } else if (tab.name === 'CAPTCHA') {
    loadCaptchaConfigs()
  }
}

// 标签页变化处理
const handleTabChange = (tabName) => {
  // 保存当前选中的标签页到localStorage
  localStorage.setItem('systemConfigActiveGroup', tabName)

  if (tabName === 'EMAIL') {
    loadEmailConfigs()
  } else if (tabName === 'PHONE') {
    loadPhoneConfigs()
  } else if (tabName === 'CAPTCHA') {
    loadCaptchaConfigs()
  }
}

// 监听activeGroup变化，自动加载对应配置
watch(activeGroup, (newGroup, oldGroup) => {
  console.log('标签页切换:', oldGroup, '->', newGroup)
  // 只有在标签页真正发生变化时才加载配置，避免重复加载
  if (newGroup !== oldGroup) {
    if (newGroup === 'EMAIL') {
      loadEmailConfigs()
    } else if (newGroup === 'PHONE') {
      loadPhoneConfigs()
    } else if (newGroup === 'CAPTCHA') {
      loadCaptchaConfigs()
    }
  }
})

// 初始化页面数据
const initPage = () => {
  // 确保有有效的标签页
  if (!activeGroup.value || !['EMAIL', 'PHONE', 'CAPTCHA', 'SYSTEM'].includes(activeGroup.value)) {
    activeGroup.value = 'EMAIL'
    localStorage.setItem('systemConfigActiveGroup', 'EMAIL')
  }

  // 立即加载对应的配置数据
  if (activeGroup.value === 'EMAIL') {
    loadEmailConfigs()
  } else if (activeGroup.value === 'PHONE') {
    loadPhoneConfigs()
  } else if (activeGroup.value === 'CAPTCHA') {
    loadCaptchaConfigs()
  }
}

// 验证码预览成功处理
const handlePreviewSuccess = (data) => {
  console.log('验证码预览验证成功:', data)
  ElMessage.success('验证码验证成功')
}

// 验证码预览失败处理
const handlePreviewFailed = () => {
  console.log('验证码预览验证失败')
}

onMounted(() => {
  console.log('系统配置页面已加载，当前标签页:', activeGroup.value)
  // 延迟一下初始化，确保DOM已经渲染完成
  nextTick(() => {
    initPage()
  })
})
</script>

<style scoped>
.system-config-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 8px;
}

.page-header p {
  color: #909399;
  margin: 0;
}

.config-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
}

.section-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.section-header h3 {
  color: #303133;
  margin-bottom: 8px;
}

.section-header p {
  color: #909399;
  margin: 0;
}

.config-form {
  max-width: 600px;
}

.config-desc {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.config-status {
  margin-top: 20px;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.status-item {
  display: flex;
  align-items: center;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs__content) {
  margin-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-switch__text) {
  font-size: 12px;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 500;
}

.config-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.config-item:last-child {
  border-bottom: none;
}

.config-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.config-label .el-icon {
  color: #909399;
  cursor: help;
}

.unit {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.captcha-preview {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px dashed #dcdfe6;
}
</style>
